package com.how2java.tmall.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.how2java.tmall.config.AlipayConfig;
import com.how2java.tmall.config.AlipayConfigs;
import com.how2java.tmall.pojo.Deposit;
import com.how2java.tmall.service.DepositService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import static java.lang.System.out;

@Controller
public class depController {

    @Autowired
    DepositService depositService;

    @RequestMapping("/dep")
    public void depController(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfigs.gatewayUrl,
                AlipayConfigs.APP_ID,
                AlipayConfigs.APP_PRIVATE_KEY,
                "json",
                AlipayConfigs.charset,
                AlipayConfigs.ALIPAY_PUBLIC_KEY,
                AlipayConfigs.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfigs.return_url);
        alipayRequest.setNotifyUrl(AlipayConfigs.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(request.getParameter("deposit_id").getBytes("ISO-8859-1"), "UTF-8");
        //付款金额，必填
        String total_amount = new String(request.getParameter("money").getBytes("ISO-8859-1"), "UTF-8");
        //订单名称，必填
        String subject = new String(request.getParameter("user_id").getBytes("ISO-8859-1"), "UTF-8");

        //                new String(request.getParameter("user_id").getBytes("ISO-8859-1"), "UTF-8");
//        //订单名称，必填
//        String subject = new String(request.getParameter("user_id").getBytes("ISO-8859-1"), "UTF-8");
        //商品描述，可空
//        String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"), "UTF-8");


        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
//                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"5m\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + AlipayConfigs.charset);
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }
/*
*       退款
* */
    @RequestMapping("/refund")
    public Object refundController(HttpServletResponse response,HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
        out.println("refund----方法进入");
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
        AlipayConfig.gatewayUrl,
                AlipayConfigs.APP_ID,
                AlipayConfigs.APP_PRIVATE_KEY,
                "json",
                AlipayConfigs.charset,
                AlipayConfigs.ALIPAY_PUBLIC_KEY,
                AlipayConfigs.sign_type);
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        String out_trade_no = new String(request.getParameter("deposit_id").getBytes("ISO-8859-1"), "UTF-8");
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //请二选一设置
        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = new String(request.getParameter("refund_amount").getBytes("ISO-8859-1"), "UTF-8");
        //退款的原因说明
        String refund_reason = new String(request.getParameter("WIDTRrefund_reason").getBytes("ISO-8859-1"), "UTF-8");
        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
        String out_request_no = new String(request.getParameter("WIDTRout_request_no").getBytes("ISO-8859-1"), "UTF-8");

        Deposit deposit = new Deposit();
        int deposit_id = Integer.parseInt(out_trade_no);
        float money = Float.parseFloat(refund_amount);
        deposit.setDepositId(deposit_id);
        deposit.setCreateTime(new Date());
        deposit.setStatus(0);
        deposit.setMoney(money);
        deposit.setUserId(87);
        deposit.setGoodsId(87);
        depositService.update(deposit);

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"trade_no\":\"" + trade_no + "\","
                + "\"refund_amount\":\"" + refund_amount + "\","
                + "\"refund_reason\":\"" + refund_reason + "\","
                + "\"out_request_no\":\"" + out_request_no + "\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();

        //输出
        out.println(result);
        return "fore/ok";
    }
}
